package com.xindacloud.sms.adapter.service.sms.impl;

import com.nexmo.client.NexmoClientException;
import com.nexmo.client.sms.SmsSubmissionResponse;
import com.nexmo.client.sms.messages.TextMessage;
import com.xindacloud.sms.adapter.bo.SubmitMessageBO;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.factory.NexmoClientFactory;
import com.xindacloud.sms.adapter.service.sms.ISubmitMessageService;
import com.xindacloud.sms.adapter.utils.MessageTypeHelp;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import com.xindacloud.sms.adapter.vo.SubmitMessageResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("nexmoSubmitMessageService")
@Slf4j
public class NexmoSubmitMessageServiceImpl implements ISubmitMessageService<SubmitMessageBO, SubmitMessageResultVO> {


    private final NexmoClientFactory nexmoClientFactory;

    @Autowired
    public NexmoSubmitMessageServiceImpl(NexmoClientFactory nexmoClientFactory) {
        this.nexmoClientFactory = nexmoClientFactory;
    }

    @Override
    public SubmitMessageResultVO submitMessage(SubmitMessageBO submitMessageBO) {

        final String recipient = submitMessageBO.getRecipient();
        final String senderId = submitMessageBO.getSenderId();
        final String messageBody = submitMessageBO.getMessageBody();

        try {
            TextMessage message = new TextMessage(senderId, recipient, messageBody, MessageTypeHelp.isUnicode(messageBody));
            message.setStatusReportRequired(true);
            message.setCallbackUrl(submitMessageBO.getCallBackUrl());
            SmsSubmissionResponse response = nexmoClientFactory.getNexmoClient(submitMessageBO.getApiKey(),
                    submitMessageBO.getApiSecret(), submitMessageBO.getApiUrl()).getSmsClient().submitMessage(message);
            SubmitMessageResultVO submitMessageResultVO = new SubmitMessageResultVO();
            response.getMessages()
                    .forEach(mp -> {
                        submitMessageResultVO.setErrorText(mp.getErrorText());
                        submitMessageResultVO.setMessageId(mp.getId());
                        submitMessageResultVO.setNetwork(mp.getNetwork());
                        submitMessageResultVO.setSubmitStatus(0);
                    });
            return submitMessageResultVO;
        } catch (NexmoClientException e) {
            log.error("#### 发送短信异常:{}", e.getMessage(), e);
            throw new ServiceException("短信发送异常".concat(e.getMessage()), UnionResultHelp.StatusEnum.BadRequest.code());
        }
    }

}
